package com.yujistu.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.yujistu.R;
import com.yujistu.fragment.HomeFragment;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Win on 2015/11/5.
 */
public class GalleryView extends RelativeLayout {

    public GalleryPagerAdapter  mGalleryPagerAdapter;
    private Context  mContext;
    private View  mGallery;
    private ArrayList mGalleryData;
    private ViewPager mGalleryViewPager;
    private ArrayList<ImageView>  mGalleryImageViewArray;
    private int  mGalleryNumber;
    private int  mPageIndex = 0;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 100:
                    ++mPageIndex;
                    mGalleryViewPager.setCurrentItem(mPageIndex);
                    break;
                case 101:
                    --mPageIndex;
                    mGalleryViewPager.setCurrentItem(mPageIndex);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private onGalleryIntentListener mListener;
    /* 轮播时长 */
    private long  mShowTime = 3000;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private boolean  mDirectionFlag = true; // 方向标志， true从左往右

    private int mWidth;
    private int mHeight;

    public GalleryView(Context context) {
        super(context);
        mContext = context;
        mGallery = LayoutInflater.from(context).inflate(R.layout.home_gallery_viewpager, null, true);
        addView(mGallery, 0);
    }

    /*public GalleryView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public GalleryView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }*/

    public void setParams(ArrayList<String> list) {   //处理来自缓存的数据
        mGalleryNumber = list.size();
        int num = mGalleryNumber + 2;
        mGalleryData = new ArrayList();
        for (int i = 0; i < num; i++){
            if(i == 0){
               mGalleryData.add(list.get(mGalleryNumber - 1));
            }else if(i == num - 1){
               mGalleryData.add(list.get(0));
            }else{
                mGalleryData.add(list.get( i - 1));
            }
        }
        init();
    }

    private void init() {
        // 幻灯片图片
        mGalleryViewPager = (ViewPager)mGallery.findViewById(R.id.galleryVP);

        mGalleryImageViewArray = new ArrayList<ImageView>();

        for(int i=0; i<mGalleryData.size(); i++){
            final int position = i;
            ImageView galleryImageView = new ImageView(mContext);

            Glide.with(mContext.getApplicationContext()).load(mGalleryData.get(i)).centerCrop().crossFade().into(galleryImageView);

            galleryImageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListener.intentToActivity(position);
                }
            });
            galleryImageView.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                             stopSlide();
                            break;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            startSlide();
                            break;
                        case MotionEvent.ACTION_MOVE:
                        default:
                            break;
                    }
                    return false;
                }
            });
            mGalleryImageViewArray.add(galleryImageView);
        }

        mGalleryViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            // arg0:当前页面，即你点击滑动的页面
            //  arg1:当前页面偏移的百分比
            //  arg2:当前页面偏移的像素位置
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (positionOffsetPixels == 0.0) {
                    setCurrentItem();
                }
            }

            @Override
            public void onPageSelected(int position) {
                 mPageIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mPageIndex = 1;

        mGalleryPagerAdapter = new GalleryPagerAdapter();
        mGalleryViewPager.setAdapter(mGalleryPagerAdapter);
        mGalleryViewPager.setCurrentItem(mPageIndex, false);

        // 自动翻页
        startSlide();
    }

    private void startSlide() {
       if(null != mTimer){
           stopSlide();
       }
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
               Message msg = new Message();
               if(mDirectionFlag){
                   msg.what = 100;
               }else{
                   msg.what = 101;
               }
                mHandler.sendMessage(msg);
            }
        };
        mTimer.schedule(mTimerTask, mShowTime, mShowTime); //使用了定时调度
    }

    private void stopSlide() {
        if(null != mTimer){
            mTimer.cancel();
            mTimer = null;
        }
        if(mTimerTask != null){
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    private void setCurrentItem() {
        // 拉到下方会出现mPageIndex一直增长的情况
        if(mPageIndex > mGalleryData.size()){
            mPageIndex = 0;
         }
        if(mPageIndex == 0){
           mPageIndex = mGalleryNumber;
           mGalleryViewPager.setCurrentItem(mPageIndex, false);
        }else if(mPageIndex == mGalleryData.size() - 1 || mPageIndex == mGalleryData.size()){
            mPageIndex = 1;
            mGalleryViewPager.setCurrentItem(mPageIndex, false);
        }else{
            mGalleryViewPager.setCurrentItem(mPageIndex);
        }
    }

    public void setOnGalleryIntentListener(onGalleryIntentListener mListener) {
        this.mListener = mListener;
    }

    public interface onGalleryIntentListener{
        void intentToActivity(int position);
    }

    public class GalleryPagerAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return mGalleryData.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager)container).addView(mGalleryImageViewArray.get(position));
            return mGalleryImageViewArray.get(position);
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager)container).removeView((View)object);
        }
    }
}
